package bll

import (
	"context"
	"maya-service/store/mysql"

	"maya-service/model"
	"maya-service/model/entity"
	"maya-service/model/mapping"
	"maya-service/store"
	"time"
)

type quanxiQuestion struct {
	iQuanxiQuestion store.IQuanxiQuestion
}

var QuanxiQuestion = &quanxiQuestion{
	iQuanxiQuestion: mysql.QuanxiQuestion,
}

func init() {
	Register(QuanxiQuestion)
}

func (a *quanxiQuestion) init() func() {
	return func() {}
}

// Create
func (a *quanxiQuestion) Create(ctx context.Context, in *model.QuanxiQuestionCreateRequest) (int64, error) {
	c := buildQuanxiQuestion(in)
	return a.iQuanxiQuestion.Create(ctx, c)
}

// Update
func (a *quanxiQuestion) Update(ctx context.Context, in *model.QuanxiQuestionUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	if in.UserId != nil {
		dict["user_id"] = in.UserId
	}

	if in.Question != nil {
		dict["question"] = in.Question
	}

	if in.Options != nil {
		dict["options"] = in.Options
	}

	if in.Type != nil {
		dict["type"] = in.Type
	}

	if in.CreatedAt != nil {
		dict["created_at"] = in.CreatedAt
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	// do other update here
	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt
	return a.iQuanxiQuestion.Update(ctx, in.Id, dict)
}

// Delete
func (a *quanxiQuestion) Delete(ctx context.Context, in *model.QuanxiQuestionDeleteRequest) error {
	return a.iQuanxiQuestion.Delete(ctx, in.Id)
}

// List
func (a *quanxiQuestion) List(ctx context.Context, in *model.QuanxiQuestionListRequest) (*model.QuanxiQuestionListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.QuanxiQuestion
		out   = &model.QuanxiQuestionListResponse{}
	)

	if total, list, err = a.iQuanxiQuestion.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = mapping.QuanxiQuestionsEntityToDto(list)

	return out, nil
}

// Find
func (a *quanxiQuestion) Find(ctx context.Context, in *model.QuanxiQuestionInfoRequest) (*model.QuanxiQuestionInfo, error) {
	var (
		err  error
		data *entity.QuanxiQuestion
		out  = &model.QuanxiQuestionInfo{}
	)

	if data, err = a.iQuanxiQuestion.Find(ctx, in); err != nil {
		return nil, err
	}

	out = mapping.QuanxiQuestionEntityToDto(data)
	return out, nil
}

// buildQuanxiQuestion build entity
func buildQuanxiQuestion(in *model.QuanxiQuestionCreateRequest) *entity.QuanxiQuestion {

	ety := &entity.QuanxiQuestion{}

	ety.UserId = in.UserId

	ety.Question = in.Question

	ety.Options = in.Options

	ety.Type = in.Type

	ety.CreatedAt = time.Now().Unix()

	ety.UpdatedAt = in.UpdatedAt

	return ety
}
